<!-- 将文章目录以树的形式展示 -->
<template>
  <el-tree :data="treeData" :expand-on-click-node="false"
           @node-click="handleNodeClick" class="tree"
           :default-expand-all="true"></el-tree>
</template>

<script setup>

import {ref, watch} from "vue";

// eslint-disable-next-line no-undef
const props = defineProps({
  html: String
});

watch(() => props.html, () => {
  setTreeDataByHtml(props.html)
})
const treeData = ref([]);
//是否找到子目录
let isFind = false;
//解析子目录
const setSubDirectory = (directory, level, label, id) => {
  //表示当前的目录层级
  const curr = directory
  //表示递归的目录层级
  const children = directory.children
  if (children.length > 0) {
    //递归子目录，同层级下，数组下标在其范围即可
    setSubDirectory(directory.children[children.length - 1], level, label, id)
  }
  //子目录已经归位
  if (isFind === true) return;
  //当前层级小于等于目录层级，表示找到了目录
  if (curr.level < level) {
    isFind = true
    curr.children.push({level, label, children: [], id})
  }
}

//解析html，生成目录树
const setTreeDataByHtml = (htmlContent) => {
  const regex = /<h(10|[1-9])>.*h(10|[1-9])>/g
  let match = htmlContent.match(regex);
  for (let i = 0; i < match.length; i++) {
    let str = match[i];
    // console.log(str)
    var id = str.match(/id=".*"/g);
    id = id[0].substring(4);
    id = id.substring(0, id.length - 1);
    const level = parseInt(str[2]);
    let label = str
    const regexLabel = /[a]>.*h(10|[1-9])>/g;
    let match1 = str.match(regexLabel);
    label = match1[0].substring(2).replace(/<.h[1-9|10]>/g, "");
    //不需要找子目录
    if (treeData.value.length === 0 || treeData.value[treeData.value.length - 1].level >= level) {
      treeData.value.push({label, level, children: [], id})
    } else {
      isFind = false
      setSubDirectory(treeData.value[treeData.value.length - 1], level, label, id)
    }
  }
}

const handleNodeClick = (data) => {
  let hTags = document.getElementById(data.id)
  hTags.scrollIntoView({
    behavior: "smooth",
    block: "start",
  });
}

</script>


<style scoped>
.tree {
  width: 15%;
  position: fixed;
  top: 10px; /* 从页面顶部的距离 */
  overflow: auto;
  height: 90%;
  width: 18%;
}

/* 整个滚动条 */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

/* 滚动条上的滚动滑块 */
::-webkit-scrollbar-thumb {
  background-color: #ffffff;
//background-color: #529be3;
  /* 关键代码 */
  background-image: -webkit-linear-gradient(45deg,
  rgba(255, 255, 255, 0.4) 25%,
  transparent 25%,
  transparent 50%,
  rgba(255, 255, 255, 0.4) 50%,
  rgba(255, 255, 255, 0.4) 75%,
  transparent 75%,
  transparent);
  border-radius: 32px;
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  background-color: #ffffff;
  border-radius: 32px;
}

</style>
